package com.yx.cloud.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;
import android.widget.Toast;

import com.aaa.async.DoneCallback;
import com.aaa.async.FailCallback;
import com.google.gson.Gson;
import com.iot.base.service.req.ConfigRecordSaveParam;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.iot.product.sweeper.bean.Robot;
import com.iot.sweeper.AppContext;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.bean.CreateDeviceParam;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.databinding.DeviceconnectActivityBinding;
import com.yx.cloud.network.ap.ApDataHandler;
import com.yx.cloud.network.ap.ApDataPacket;
import com.yx.cloud.network.ap.TcpServer;
import com.yx.cloud.network.ap.WifiNetUtil;
import com.yx.cloud.network.ble.BleException;
import com.yx.cloud.network.ble.BleProtocol;
import com.yx.cloud.network.ble.BluetoothModel;
import com.yx.cloud.network.ble.Cmd;
import com.yx.cloud.network.ble.yx.YxBleDataPacket;
import com.yx.cloud.product.laser.tuyapublic.BluetoothScanDeviceBean;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LocationUtils;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.SharedPrefsUtil;
import com.yx.cloud.utils.StringUtils;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.utils.WifiManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

/**
 * 设备连接界面
 */
public class DeviceConnectActivity2 extends BaseActivity {
    private static final String TAG = "DeviceConnectActivity2";
    private WifiManager xw;
    private boolean b, b1;
    private Animation animation;
    private Message mes;
    private String value;
    private String deviceName = "";
    private TimeEZMode ez_mode;
    private TimeBluetoothMode1 bluetooth_mode1;
    private DeviceconnectActivityBinding binding;
    private CreateDeviceParam config_bean;
    private String qrConfigToken;
    private Handler handler;
    private BluetoothModel model;
    private int bleConnectFrequency = 0;//连接蓝牙失败次数
    private String network, bleAddress;
    private BluetoothScanDeviceBean bluetoothData;
    private List<Robot> newDeviceList;
    private String sendBleData = "";

    @Override
    public void onCreate() {
        binding = DeviceconnectActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initData();
    }

    private void initData() {
        handler = new Handler() {
            @SuppressLint("HandlerLeak")
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                int mmsg = msg.arg1;
                if (mmsg == 1) {
                    binding.connectLoadingStepOne.clearAnimation();
                    binding.connectLoadingStepOne.setImageResource(R.mipmap.succeed_icon);
                    binding.connectLoadingStepTwo.startAnimation(animation);
                    binding.tvStepTwo.setTextColor(getResources().getColor(R.color.textview_color1));
                    //给机器发送帐号密码
                    if ("bluetooth".equals(network)) {
                        LogUtils.i(" :----其他机型蓝牙xxxxxxxxxx-配网模式 : ");
                        //连接蓝牙
                        bleAddress = bluetoothData.getAddress();
                        connectBLE();
                    } else if ("qrCode".equals(network)) {
                        //预留二维码配网
                    } else {
                        LogUtils.i(" :----xxxxxxxxxx-AP : " + value);
                        mes = new Message();
                        mes.arg1 = 2;
                        handler.sendMessage(mes);
                    }

                } else if (mmsg == 2) {
                    binding.connectLoadingStepTwo.clearAnimation();
                    binding.connectLoadingStepTwo.setImageResource(R.mipmap.succeed_icon);
                    binding.tvStepThree.setTextColor(getResources().getColor(R.color.textview_color1));
                    binding.connectLoadingStepThree.startAnimation(animation);
                    if ("wifi".equals(network)) {
                        startConfig();
                    }
                } else if (mmsg == 3) {
                    if ("bluetooth".equals(network)) {
                        if (model != null) {
                            model.disconnect();//断开蓝牙连接
                        }
                    }
                    binding.connectLoadingStepTwo.clearAnimation();
                    binding.connectLoadingStepTwo.setImageResource(R.mipmap.succeed_icon);
                    binding.connectLoadingStepThree.clearAnimation();
                    binding.connectLoadingStepThree.setImageResource(R.mipmap.succeed_icon);
                    Robot device = (Robot) msg.obj;
                    String locations = LocationUtils.getInstance().convertAddress(DeviceConnectActivity2.this);
                    ConfigRecordSaveParam param = new ConfigRecordSaveParam();
                    param.setAddress(locations);
                    param.setMac(device.getFirmwareInfo().getMac());
                    param.setReason("AP success");
                    param.setResult("success");
                    param.setSub_type(device.getProductId());
                    param.setThing_name(device.getDeviceId());
                    AppContext.getAccountService().configRecordSave(param);

                    if (device != null) {
                        mQueryThing = false;
                        AppContext.get().connectDevice(device);
                        deviceName = device.getName();
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        Intent_utils.enterIntentContext(DeviceConnectActivity2.this, ConnectSuccessActivity.class, "deviceName", deviceName);
                        finish();
                    } else {
                        ToastUtil.show(DeviceConnectActivity2.this, "返回 obj为 NULL", Toast.LENGTH_LONG);
                    }
                }
            }
        };

        network = getIntent().getStringExtra("network");
        config_bean = (CreateDeviceParam) getIntent().getSerializableExtra("config_bean");

        LogUtils.i("------------------wwwww--------------Device_type: " + config_bean.getDevice_type());

        animation = AnimationUtils.loadAnimation(this, R.anim.ceconnect_wifi_step);
        LinearInterpolator lin = new LinearInterpolator(); //匀速
        animation.setInterpolator(lin);
        binding.connectLoadingStepOne.startAnimation(animation);
        binding.tvStepOne.setTextColor(getResources().getColor(R.color.textview_color1));
        binding.ivDeviceConnectReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                outConnectDialog(getString(R.string.N_Connect_Exit), "");
            }
        });

        if ("bluetooth".equals(network)) {
            //蓝牙配网
            bluetoothData = (BluetoothScanDeviceBean) getIntent().getSerializableExtra("bluetoothData");
            String source = bluetoothData.getSource();
            if ("yugong".equals(source)) {
                //除X5外的其他机型蓝牙配网
                mes = new Message();
                mes.arg1 = 1;
                handler.sendMessage(mes);
            }
        } else if ("qrCode".equals(network)) {
            qrConfigToken = getIntent().getStringExtra("qrConfigToken");
            mes = new Message();
            mes.arg1 = 1;
            handler.sendMessage(mes);
            bluetooth_mode1 = new TimeBluetoothMode1(5000, 1000);
            bluetooth_mode1.start();
        } else {
            value = SharedPrefsUtil.getValue(this, "EZandAP", "EZandAP", "");
            xw = new WifiManager(this);
            mes = new Message();
            mes.arg1 = 1;
            handler.sendMessage(mes);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_GET_DEVICE_LIST:
                //拿到设备列表循环比对
                if (event.isResult()) {
                    newDeviceList = (List<Robot>) event.getContent();
                    if (newDeviceList.size() > 0) {
                        for (int i = 0; i < newDeviceList.size(); i++) {
                            String deviceId = newDeviceList.get(i).getDeviceId();
                            if (deviceId.equals(config_bean.getThingname())) {
                                mQueryThing = false;
                                //配网成功 配网是否成功对比标记，在轮询中使用
                                handler.removeCallbacks(null);
                                mes = new Message();
                                mes.arg1 = 3;
                                mes.obj = newDeviceList.get(i);
                                handler.sendMessage(mes);
                            }
                        }
                    }
                }
                break;
        }
    }

    private void connectBLE() {
        LogUtils.i("配网 连接 设备 address " + bleAddress);
        if (model == null) {
            model = BluetoothModel.getInstance();
        }
        model.connect(bleAddress).done(new DoneCallback<Void>() {
            @Override
            public void onDone(Void unused) {
                LogUtils.i("配网 连接 onDone");
                mes = new Message();
                mes.arg1 = 2;
                handler.sendMessage(mes);
                sendBleData = new Gson().toJson(config_bean);
                LogUtils.ls("配网 连接 下发给机器的数据 ：" + sendBleData);
                Cmd cmd = BleProtocol.netconfig(sendBleData);
                model.send(cmd);
                queryThread = new Thread(queryRun);
                queryThread.start();//开始轮询
            }
        }).fail(new FailCallback<BleException>() {
            @Override
            public void onFail(BleException e) {
                LogUtils.i("配网 连接 onFail");
                if (bleConnectFrequency == 10) {
                    mQueryThing = false;
                    ToastUtil.show(DeviceConnectActivity2.this, getString(R.string.N_Connect_No), Toast.LENGTH_SHORT);
                    netWorkError(getString(R.string.N_Connect_No));
                } else if (bleConnectFrequency >= 0) {
                    bleConnectFrequency++;
                    try {
                        Thread.sleep(1500);
                    } catch (InterruptedException ex) {
                        e.printStackTrace();
                    }
                    connectBLE();
                }
            }
        });
    }

    private Thread apConfig, queryThread;

    @SuppressLint({"ServiceCast", "WifiManagerLeak"})
    private void startConfig() {
        LogUtils.i("AP 配网 startConfig ：");
        queryThread = new Thread(queryRun);
        queryThread.start();
        apConfig = new Thread(startConfig);
        apConfig.start();
    }

    private boolean isConnected;
    private int socketConnectedfrequency = 0;
    private Runnable startConfig = new Runnable() {
        @Override
        public void run() {
            //这里进行区分使用那种方式进行AP配网
            LogUtils.i("N5 startConfig ：" + config_bean.getDevice_type());
            if (config_bean.getDevice_type().equals("n5-full")) {
                isConnected = gyroConnected();
                LogUtils.i("N5 isConnected ：" + isConnected);
                while (!isConnected) {
                    if (socketConnectedfrequency < 10) {
                        socketConnectedfrequency++;
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        isConnected = gyroConnected();
                        LogUtils.i("N5 startConfig 发送次数" + socketConnectedfrequency);
                    } else {
                        ToastUtil.show(DeviceConnectActivity2.this, getString(R.string.N_Connect_No), Toast.LENGTH_SHORT);
                    }
                }
                b1 = xw.connectAPWithScanResult(Constants.wifi_Name, Constants.wifi_Pass);
                Log.i(TAG, Constants.wifi_Name + ":" + Constants.wifi_Pass + " : N5--配网--b1b1b1b1b1b1b1b1b1---->" + b1);
            } else {
                socketConnected();
            }
        }
    };

    /**
     * N5机型AP配网，使用局域网进行数据传输
     *
     * @return
     */
    private boolean gyroConnected() {
        try {
//            LogUtils.i("--------------------------------cacert: " + config_bean.getCacert());
//            LogUtils.i("--------------------------------cert :" + config_bean.getCert());
//            LogUtils.i("--------------------------------private_key: " + config_bean.getPrivate_key());
//            LogUtils.i("--------------------------------endpoint: " + config_bean.getEndpoint());
//            LogUtils.i("--------------------------------region_name: " + config_bean.getRegion_info());
//            LogUtils.i("--------------------------------thing_name :" + config_bean.getThingname());
//            LogUtils.i("--------------------------------timestamp_s: " + config_bean.getTimestamp_s());
//            LogUtils.i("--------------------------------Wifi_name: " + config_bean.getWifi_name());
//            LogUtils.i("--------------------------------Wifi_password :" + config_bean.getWifi_password());
//            LogUtils.i("--------------------------------User_account: " + config_bean.getUser_account());
//            LogUtils.i("--------------------------------App_info: " + config_bean.getApp_info());
//            LogUtils.i("--------------------------------Device_type: " + config_bean.getDevice_type());
            String s = new WifiNetUtil().sendPost("http://192.168.99.1/", new Gson().toJson(config_bean), null, 3000, 3000);
            JSONObject jsonObject = new JSONObject(s);
//            String thing_name = jsonObject.optString("thing_name");
            int code = jsonObject.optInt("result_code");
            LogUtils.i("N5 数据发送结果：" + s);
            Thread.sleep(500);
            if (code > -1) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private void socketConnected() {
        isConnected = TcpServer.startClient(DeviceConnectActivity2.this, TcpServer.HOST, TcpServer.PORT);//"192.168.137.1"
        LogUtils.i("AP 配网 socket 连接状态 ：" + isConnected);
        if (isConnected) {
            String config = new Gson().toJson(config_bean);
            LogUtils.i("AP 配网 数据下发 ：" + config);
            Cmd cmd = BleProtocol.netconfig(config);

            List<ApDataPacket> apDataPackets = ApDataHandler.packageData(cmd);
            try {
                TcpServer.writeMsg(apDataPackets);
                LogUtils.i("AP 配网 socket 发送完毕 ：");
                TcpServer.closeConnection();
                xw.disconnectWifi();
                Log.i(TAG, " :--配网--断开当前连接设备热点---->");
                //连接路由器,接收回调信息,连接10次
                b1 = xw.connectAPWithScanResult(Constants.wifi_Name, Constants.wifi_Pass);
                Log.i(TAG, Constants.wifi_Name + ":" + Constants.wifi_Pass + " :--配网--b1b1b1b1b1b1b1b1b1---->" + b1);

            } catch (IOException e) {
                Log.i(TAG, " :--配网--异常 111---->");
                e.printStackTrace();
            } catch (InterruptedException e) {
                Log.i(TAG, " :--配网--异常 2222---->");
                e.printStackTrace();
                apConfig.interrupt();
            }
        } else {
            LogUtils.i("AP 配网 socket 失败次数 ：" + socketConnectedfrequency);
            if (socketConnectedfrequency < 10) {
                socketConnectedfrequency++;
                try {
                    Thread.sleep(3000);
                    socketConnected();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    apConfig.interrupt();
                }
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i(TAG, " socket 通道 连接失败");
                        ToastUtil.show(DeviceConnectActivity2.this, getString(R.string.N_Connect_No), Toast.LENGTH_SHORT);
                    }
                });
            }
        }
    }

    private boolean mQueryThing = true;
    private int mPollingFrequency = 0;

    private Runnable queryRun = new Runnable() {
        @Override
        public void run() {
            while (mQueryThing) {
                if (mPollingFrequency < 40) {
                    mPollingFrequency++;
                    try {
                        Thread.sleep(5000);
                        LogUtils.i("配网 开启轮询----------");
                        AppContext.getAccountService().getDeviceList();//轮询配网结果
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        queryThread.interrupt();
                    }
                } else {
                    mQueryThing = false;
                    netWorkError(getString(R.string.N_Connect_No));
                }
            }
        }
    };

    private void outConnectDialog(String dialogTitle, String content) {
        Dialog dialog = new Dialog(DeviceConnectActivity2.this);
        dialog.setContentView(R.layout.outlogin_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_outLoginConfirm);
        TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_outLoginCancel);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_dialogTitle);
        TextView mContent = dialog.findViewById(R.id.tv_content);

        mTvDialogTitle.setText(dialogTitle);
        mContent.setText(content);
        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                mQueryThing = false;
                if ("bluetooth".equals(network)) {
                    if (model != null) {
                        model.disconnect();//断开蓝牙连接
                    }
                } else if ("qrCode".equals(network)) {
                    //停止配网
                } else {
                    //停止配网
                    TcpServer.closeConnection();//关闭TCP连接
                    if (apConfig != null) {
                        apConfig.interrupt();
                    }
                }
                Log.i(TAG, " :----bbbbbb- 取消配网---> : ");
                dialog.dismiss();
                Intent_utils.backIntent(DeviceConnectActivity2.this);
            }
        });
        mBtnOutLoginCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    public class TimeEZMode extends CountDownTimer {

        public TimeEZMode(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            mes = new Message();
            mes.arg1 = 2;
            handler.sendMessage(mes);
        }
    }

    public class TimeBluetoothMode1 extends CountDownTimer {

        public TimeBluetoothMode1(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            mes = new Message();
            mes.arg1 = 2;
            handler.sendMessage(mes);
        }
    }


    private void netWorkError(String src) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                binding.connectLoadingStepOne.clearAnimation();
                binding.connectLoadingStepOne.setImageResource(R.mipmap.nonsupport_icon);
                binding.connectLoadingStepTwo.clearAnimation();
                binding.connectLoadingStepTwo.setImageResource(R.mipmap.nonsupport_icon);
                binding.connectLoadingStepThree.clearAnimation();
                binding.connectLoadingStepThree.setImageResource(R.mipmap.nonsupport_icon);
                binding.lottieAnimationView.clearAnimation();
                ToastUtil.show(DeviceConnectActivity2.this, src, Toast.LENGTH_SHORT);
                String locations = LocationUtils.getInstance().convertAddress(DeviceConnectActivity2.this);
                ConfigRecordSaveParam param = new ConfigRecordSaveParam();
                param.setAddress(locations);
                param.setMac("");
                param.setThing_name(config_bean.getThingname());//getThingname
                param.setReason("AP " + src);
                param.setResult("fail");
                param.setSub_type(config_bean.getDevice_type());//getDevice_type
                AppContext.getAccountService().configRecordSave(param);
                if ("bluetooth".equals(network)) {
                    if (model != null) {
                        model.disconnect();//断开蓝牙连接
                    }
                } else {
                    //AP
                    TcpServer.closeConnection();//关闭TCP连接
                }
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //配网失败
                Intent_utils.enterIntent(DeviceConnectActivity2.this, ConnectionFailActivity.class);
                finish();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.i("onDestroy===============");
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        bleConnectFrequency = -1;
        mQueryThing = false;
        if ("bluetooth".equals(network)) {
            if (model != null) {
                model.disconnect();//断开蓝牙连接
                LogUtils.i("onDestroy===============disconnect");
            }
        } else if ("wifi".equals(network)) {
            //AP
            TcpServer.closeConnection();//关闭TCP连接
        }
        if (apConfig != null) {
            apConfig.interrupt();
        }
        if (queryThread != null) {
            queryThread.interrupt();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            outConnectDialog(getString(R.string.N_Connect_Exit), "");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
